package com.aauedu.springboot.controller;

import com.aauedu.springboot.bean.Admin;
import com.aauedu.springboot.bean.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Controller
public class AdminController {
    //响应用户的登录请求
    @PostMapping("/login")
    public String login(Admin admin, HttpSession session, Model model) {
        String name = admin.getName();
        String password = admin.getPassword();
        //验证用户是否合法
        if (StringUtils.hasText(name) && password.equals("666")) {
            //合法，重定向到manage.html
            //JavaWeb，不使用请求转发是防止表单刷新页面会重复提交
            //这里写的是manage.html，因为这样可以更加明确的表示到哪个页面
            //manage.html表示要去找方法的映射路径为manage.html
            session.setAttribute("loginAdmin", admin);
            return "redirect:/manage.html";
        } else {
            //不合法，就重新登录
            model.addAttribute("msg", "用户/密码不正确");
            return "adminLogin";
        }
    }

    //处理用户的请求到manage.html
    @GetMapping("/manage.html")
    public String manage(Model model, HttpSession session) {
        //这里暂时使用session验证，后面统一使用拦截器来验证
        Object loginAdmin = session.getAttribute("loginAdmin");
        if (loginAdmin != null) {
            //可以这里使用集合-模拟用户数据，放入到request域中，并展示
            List<User> userList = new ArrayList<>();
            userList.add(new User(1, "关羽", "666666", 25, "gy@sohu.com"));
            userList.add(new User(2, "张飞", "666666", 20, "zf@sohu.com"));
            userList.add(new User(3, "赵云", "666666", 22, "zy@sohu.com"));
            userList.add(new User(4, "马超", "666666", 24, "mc@sohu.com"));
            userList.add(new User(5, "黄忠", "666666", 56, "hz@sohu.com"));
            model.addAttribute(userList);
            return "manage";//这里才是我们的视图解析到  /templates/manage.html
        } else {
            //这里返回登录页，并返回提示
            model.addAttribute("msg", "你没有登录，请重新登录");
           return "adminLogin"; //请求转发到adminLogin.html
        }


    }

}

